package br.com.mmm.javacenter.framework.view.tiles.listener;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletContext;

import org.apache.tiles.TilesApplicationContext;
import org.apache.tiles.context.TilesRequestContextFactory;
import org.apache.tiles.definition.DefinitionsFactoryException;
import org.apache.tiles.factory.BasicTilesContainerFactory;

public class WildcardServletTilesApplicationContext extends BasicTilesContainerFactory {

	public WildcardServletTilesApplicationContext(ServletContext servletContext) {
		super();
	}
	@Override
	protected List<URL> getSourceURLs(
			TilesApplicationContext applicationContext,
			TilesRequestContextFactory contextFactory) {


	    List<URL> urls = new ArrayList<URL>();
	    try {
	        Set<URL> urlSet = applicationContext
	                .getResources("/WEB-INF/tiles-defs*.xml");
	        for (URL url : urlSet) {
	            String externalForm = url.toExternalForm();
	            if (externalForm.indexOf('_', externalForm.lastIndexOf("/")) < 0) {
	                urls.add(url);
	            }
	        }
	        urls.add(applicationContext.getResource(
	                "classpath:/org/apache/tiles/classpath-defs.xml"));
	    } catch (IOException e) {
	        throw new DefinitionsFactoryException(
	                "Cannot load definition URLs", e);
	    }
	    return urls;
	}
	
}

